#include "DataStructures.h"
#include <malloc.h>
#include <stdlib.h>

void initList(List * list) {
		list->head = NULL;
		list->tail = NULL;
		list->curr = NULL;
		list->size = 0;
}

void pushBack(List * list, int val) {
	ListNode * node = (ListNode *)malloc(sizeof(ListNode));
	node->val = val;
	node->next = NULL;
	node->prev = list->tail;
	if (list->tail != NULL)
		list->tail->next = node;
	list->tail = node;
	if (list->head == NULL)
		list->head = node;
	list->size++;
}

void initQueue(Queue * queue) {
		queue->head = NULL;
		queue->current = NULL;
		queue->size = 0;
}

void destroyList(List * list) {
	
	ListNode * pNode, * tmpNode;
	
	if (list == NULL)
		return;

	pNode = list->head;
	
	while (pNode != NULL) {
		tmpNode = pNode->next;
 		free(pNode);
		pNode = tmpNode;
	}
	list->head = NULL;
	list->tail = NULL;
	list->curr = NULL;

	list->size = 0;

}

void initQueues(Queue * queues, int N) {

	int i;

	for (i = 0; i < N; i++) {
		initQueue(&queues[i]);
	}

}


void destroyQueue(Queue * queue) {

	Packet * tmp;

	if (queue == NULL)
		return;

	while (queue->head != NULL) {
		tmp = queue->head->next;
		free(queue->head);
		queue->head = tmp;
	}
	
	queue->size = 0;

}

void insertToQueue(Queue * queue, Packet * packet) {
	
	packet->next = NULL;

	if (queue->head == NULL)
		queue->head = packet;
	else
		queue->current->next = packet;

	queue->current = packet;
	queue->size++;
}

Packet * popQueue(Queue * queue) {
	Packet * pPacket = queue->head;
	if (queue->head == queue->current) {
		queue->head = NULL;
		queue->current = NULL;
	} else {
		queue->head = queue->head->next;
	}
	queue->size--;
	pPacket->next = NULL;
	return pPacket;
}